using DataAggregationService.Model;
using DataAggregationService.Service;
using Microsoft.Extensions.Options;

namespace DataAggregationService
{
	public class Worker : BackgroundService
	{
		private readonly ILogger<Worker> _logger;
		private readonly IDbService _dbService;
		private readonly SemaphoreSlim _semaphore;
		private readonly SyncConfig _syncConfig;

		public Worker(ILogger<Worker> logger, IOptions<SyncConfig> syncConfig, IDbService dbService)
		{
			_logger = logger;
			_syncConfig = syncConfig.Value;
			_dbService = dbService;
			_semaphore = new SemaphoreSlim(1, 1);
		}

		protected override async Task ExecuteAsync(CancellationToken stoppingToken)
		{
			while (!stoppingToken.IsCancellationRequested)
			{
				try
				{
					_logger.LogInformation("Worker running at: {Time}", DateTimeOffset.Now);

					await _semaphore.WaitAsync(stoppingToken);

					await _dbService.AggregateDataAsync();
				}
				catch (Exception ex)
				{
					_logger.LogError(ex, "An error occurred while processing data.");
				}
				finally
				{
					_semaphore.Release();
				}

				await Task.Delay(TimeSpan.FromSeconds(_syncConfig.TaskInterval), stoppingToken);
			}
		}
	}
}